import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import {
    Box,
    Button,
    Card,
    CardActions,
    CardContent,
    CardMedia,
    Container,
    Grid,
    Typography,
    FormControl,
    InputLabel,
    Select,
    MenuItem,
    TextField,
    InputAdornment,
    Chip,
    Divider,
} from '@mui/material';
import SearchIcon from '@mui/icons-material/Search';
import VisibilityIcon from '@mui/icons-material/Visibility';
import AddIcon from '@mui/icons-material/Add';
import { useAuth } from '../contexts/AuthContext';

const TemplateGallery = () => {
    const navigate = useNavigate();
    const { isAuthenticated } = useAuth();
    const [searchTerm, setSearchTerm] = useState('');
    const [categoryFilter, setCategoryFilter] = useState('all');

    // Mock template data - in a real app, this would come from an API
    const templates = [
        {
            id: 'modern-1',
            name: '现代简约',
            category: 'modern',
            description: '简洁明了的设计，突出您的技能和经验。适合大多数行业的求职者。',
            image: 'https://via.placeholder.com/300x400?text=Modern+Template',
            tags: ['简约', '专业', '通用'],
            popular: true,
        },
        {
            id: 'creative-1',
            name: '创意设计',
            category: 'creative',
            description: '独特的布局和色彩方案，展示您的创造力。适合设计、艺术等创意行业。',
            image: 'https://via.placeholder.com/300x400?text=Creative+Template',
            tags: ['创意', '色彩丰富', '设计'],
            popular: false,
        },
        {
            id: 'professional-1',
            name: '商务专业',
            category: 'professional',
            description: '传统而专业的设计，适合金融、法律、管理等传统行业的求职者。',
            image: 'https://via.placeholder.com/300x400?text=Professional+Template',
            tags: ['传统', '商务', '正式'],
            popular: true,
        },
        {
            id: 'minimal-1',
            name: '极简风格',
            category: 'minimal',
            description: '极简主义设计，只关注最重要的信息。适合经验丰富的专业人士。',
            image: 'https://via.placeholder.com/300x400?text=Minimal+Template',
            tags: ['极简', '简洁', '清晰'],
            popular: false,
        },
        {
            id: 'tech-1',
            name: '科技风格',
            category: 'tech',
            description: '现代科技感设计，突出您的技术技能。适合IT、工程等技术岗位。',
            image: 'https://via.placeholder.com/300x400?text=Tech+Template',
            tags: ['科技', '现代', '技术'],
            popular: true,
        },
        {
            id: 'academic-1',
            name: '学术简历',
            category: 'academic',
            description: '专为学术界设计，突出您的研究、发表和教学经验。',
            image: 'https://via.placeholder.com/300x400?text=Academic+Template',
            tags: ['学术', '研究', '教育'],
            popular: false,
        },
    ];

    // Filter templates based on search term and category
    const filteredTemplates = templates.filter(template => {
        const matchesSearch = template.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
            template.description.toLowerCase().includes(searchTerm.toLowerCase()) ||
            template.tags.some(tag => tag.toLowerCase().includes(searchTerm.toLowerCase()));

        const matchesCategory = categoryFilter === 'all' || template.category === categoryFilter;

        return matchesSearch && matchesCategory;
    });

    // Handle template selection
    const handleSelectTemplate = (templateId) => {
        if (isAuthenticated) {
            navigate('/editor/new', { state: { templateId } });
        } else {
            navigate('/login', { state: { from: { pathname: '/editor/new' }, templateId } });
        }
    };

    // Categories for filter dropdown
    const categories = [
        { value: 'all', label: '全部模板' },
        { value: 'modern', label: '现代简约' },
        { value: 'creative', label: '创意设计' },
        { value: 'professional', label: '商务专业' },
        { value: 'minimal', label: '极简风格' },
        { value: 'tech', label: '科技风格' },
        { value: 'academic', label: '学术简历' },
    ];

    return (
        <Container maxWidth="lg" sx={{ mt: 4, mb: 8 }}>
            {/* Page Header */}
            <Box sx={{ mb: 6, textAlign: 'center' }}>
                <Typography variant="h3" component="h1" gutterBottom>
                    简历模板库
                </Typography>
                <Typography variant="h6" color="text.secondary" sx={{ mb: 4 }}>
                    选择一个专业设计的模板，开始创建您的简历
                </Typography>
            </Box>

            {/* Filters */}
            <Box sx={{ mb: 4 }}>
                <Grid container spacing={2} alignItems="center">
                    <Grid item xs={12} md={6}>
                        <TextField
                            fullWidth
                            placeholder="搜索模板..."
                            value={searchTerm}
                            onChange={(e) => setSearchTerm(e.target.value)}
                            InputProps={{
                                startAdornment: (
                                    <InputAdornment position="start">
                                        <SearchIcon />
                                    </InputAdornment>
                                ),
                            }}
                        />
                    </Grid>
                    <Grid item xs={12} md={6}>
                        <FormControl fullWidth>
                            <InputLabel>类别</InputLabel>
                            <Select
                                value={categoryFilter}
                                label="类别"
                                onChange={(e) => setCategoryFilter(e.target.value)}
                            >
                                {categories.map((category) => (
                                    <MenuItem key={category.value} value={category.value}>
                                        {category.label}
                                    </MenuItem>
                                ))}
                            </Select>
                        </FormControl>
                    </Grid>
                </Grid>
            </Box>

            {/* Templates Grid */}
            <Grid container spacing={4}>
                {filteredTemplates.map((template) => (
                    <Grid item key={template.id} xs={12} sm={6} md={4}>
                        <Card sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
                            <Box sx={{ position: 'relative' }}>
                                <CardMedia
                                    component="img"
                                    height="300"
                                    image={template.image}
                                    alt={template.name}
                                />
                                {template.popular && (
                                    <Chip
                                        label="热门"
                                        color="secondary"
                                        size="small"
                                        sx={{
                                            position: 'absolute',
                                            top: 16,
                                            right: 16,
                                        }}
                                    />
                                )}
                            </Box>
                            <CardContent sx={{ flexGrow: 1 }}>
                                <Typography variant="h5" component="h2" gutterBottom>
                                    {template.name}
                                </Typography>
                                <Typography variant="body2" color="text.secondary" paragraph>
                                    {template.description}
                                </Typography>
                                <Box sx={{ mt: 2 }}>
                                    {template.tags.map((tag) => (
                                        <Chip
                                            key={tag}
                                            label={tag}
                                            size="small"
                                            variant="outlined"
                                            sx={{ mr: 0.5, mb: 0.5 }}
                                        />
                                    ))}
                                </Box>
                            </CardContent>
                            <Divider />
                            <CardActions>
                                <Button
                                    size="small"
                                    startIcon={<VisibilityIcon />}
                                    onClick={() => navigate(`/resume/preview/${template.id}`)}
                                >
                                    预览
                                </Button>
                                <Button
                                    size="small"
                                    variant="contained"
                                    startIcon={<AddIcon />}
                                    onClick={() => handleSelectTemplate(template.id)}
                                    sx={{ ml: 'auto' }}
                                >
                                    使用此模板
                                </Button>
                            </CardActions>
                        </Card>
                    </Grid>
                ))}
            </Grid>

            {/* No Results */}
            {filteredTemplates.length === 0 && (
                <Box sx={{ textAlign: 'center', py: 8 }}>
                    <Typography variant="h6" color="text.secondary" gutterBottom>
                        没有找到匹配的模板
                    </Typography>
                    <Typography variant="body1" color="text.secondary">
                        请尝试不同的搜索词或筛选条件
                    </Typography>
                </Box>
            )}
        </Container>
    );
};

export default TemplateGallery; 